//
//  BBSSenderViewController.m
//  MilestoneProject
//
//  Created by 张育铭 on 2019/10/22.
//  Copyright © 2019 mac. All rights reserved.
//

#import "BBSSenderViewController.h"
#import "DoImagePickerController.h"
#import "PlaceholderTextView.h"
#import "ZXCollectionCell.h"
#import "HCEmojiKeyboard.h"

static NSString *emoji    = @"Resources.bundle/emoji";
static NSString *keyboard = @"Resources.bundle/keyboard";

#define PlaceHolder @""

@interface BBSSenderViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,ZXCollectionCellDelegate,UIActionSheetDelegate,UICollectionViewDataSource,UICollectionViewDelegate,DoImagePickerControllerDelegate>

/// 本地图片
@property (nonatomic,strong) NSMutableArray   *nativeArray;
/// 默认图片
@property (nonatomic,strong) NSMutableArray   *theimageView;

@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) UIScrollView     *scrollView;

@property (nonatomic,strong) HCEmojiKeyboard  *emojiKeyboard;

@end

@implementation BBSSenderViewController {
     
    
    //标题
    UITextField  *titleText;
    //内容
    PlaceholderTextView   *contentText;
   
}

//发布按钮
- (void)sendClicked {
    if (titleText.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请填写标题"];
            return;
        }
    if (contentText.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请填写内容"];
        return;
    }
     
    
}
 
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    /// 自定义导航栏
    [self setNavBarTitle:@"发帖"];
    [self setNavBarRightBtn:[GHOCNavBarView createNormalNaviBarBtnByTitle:@"发布" target:self action:@selector(rightBarButtonClick:)]];

    
    [self creatViewUI];
}


- (void)rightBarButtonClick:(UIButton *)sender {
    
}


- (void)creatViewUI {
    //默认图片
    [self.theimageView addObject:@"circle_add"];

    _emojiKeyboard = [HCEmojiKeyboard sharedKeyboard];

    [self.view addSubview:self.scrollView];
    self.scrollView.sd_layout
    .leftSpaceToView (self.view, 0)
    .rightSpaceToView(self.view, 0)
    .topSpaceToView  (self.view,  SCREEN_TabbarHeight)
    .bottomSpaceToView(self.view, theIsIphoneX? 83: 49);
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    titleLabel.backgroundColor = RGBCOLOR(244, 244, 244);
    titleLabel.text = @"  编辑发帖";
    titleLabel.textColor = [UIColor lightGrayColor];
    [self.scrollView addSubview:titleLabel];
        
    titleText      = [[UITextField alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(titleLabel.frame), SCREEN_WIDTH, 40)];
    titleText.font = [UIFont boldSystemFontOfSize:15];
    titleText.placeholder = @"  请输入标题(必填)";
    titleText.textColor = [UIColor blackColor];
    [self.scrollView addSubview:titleText];
        
    contentText = [[PlaceholderTextView alloc]init];
    contentText.font  = [UIFont systemFontOfSize:16];
    contentText.frame = CGRectMake(0, CGRectGetMaxY(titleText.frame), SCREEN_WIDTH, 200);
    contentText.layer.borderColor = [[UIColor grayColor]colorWithAlphaComponent:0.3].CGColor;
    contentText.layer.borderWidth = 0.5f;
    [self.scrollView addSubview:contentText];
    [contentText didChangeText:^(PlaceholderTextView *textView) {
        NSLog(@"%@",textView.text);
    }];
    
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.collectionView                 = [[UICollectionView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(contentText.frame), theIsIphoneX? 410: 320, 150) collectionViewLayout:flowLayout];
    self.collectionView.delegate        = self;
    self.collectionView.dataSource      = self;
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView registerClass:[ZXCollectionCell class] forCellWithReuseIdentifier:@"cell"];
    [self.scrollView addSubview:self.collectionView];
 
    UIButton *faceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    faceBtn.frame = CGRectMake(0, SCREEN_HEIGHT-(theIsIphoneX? 83: 49), 70, 50);
    [faceBtn setImage:[UIImage imageNamed:emoji] forState:(UIControlStateNormal)];
    [faceBtn addTarget:self action:@selector(faceBoardClick:) forControlEvents:UIControlEventTouchUpInside];
    faceBtn.tag = 0;
    [self.view addSubview:faceBtn];
}
//改变键盘状态
- (void)faceBoardClick:(UIButton *)button{
    if (button.tag == 0){
        contentText.inputView = nil;
        [button setImage:[UIImage imageNamed:emoji]    forState:UIControlStateNormal];
    } else {
        [button setImage:[UIImage imageNamed:keyboard] forState:UIControlStateNormal];
        [_emojiKeyboard setTextInput:contentText];
    }
    [contentText reloadInputViews];
    button.tag = (button.tag+1)%2;
    [contentText becomeFirstResponder];
}


#pragma mark - 添加图片
- (void)rightBtn
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"拍照"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
                                                          
                                                          [self selectPicture:0];
                                                          
                                                      }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"从手机相册中选择"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
                                                          
                                                          [self selectPicture:1];
                                                          
                                                      }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style: UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    }]];
    
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)selectPicture:(int)buttonIndex
{
    if (buttonIndex == 0) {
        //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            NSLog(@"照相机不可用");
            
            DoImagePickerController *cont = [[DoImagePickerController alloc] initWithNibName:@"DoImagePickerController" bundle:nil];
            cont.delegate = self;
            cont.nResultType = DO_PICKER_RESULT_UIIMAGE;
            cont.nMaxCount = 9;
            cont.nColumnCount = 3;
            [self presentViewController:cont animated:YES completion:nil];
        }else
        {
            UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
            picker.delegate   = self;
            picker.sourceType = sourceType;
            //进入照相界面
            [self presentViewController:picker animated:YES completion:nil];
        }
    }
    if (buttonIndex == 1) {
        DoImagePickerController *cont = [[DoImagePickerController alloc] initWithNibName:@"DoImagePickerController" bundle:nil];
        cont.delegate = self;
        cont.nResultType  = DO_PICKER_RESULT_UIIMAGE;
        cont.nMaxCount    = 9;
        cont.nColumnCount = 3;
        [self presentViewController:cont animated:YES completion:nil];
    }
}

#pragma mark - 选到图片后
- (void)didSelectPhotosFromDoImagePickerController:(DoImagePickerController *)picker result:(NSArray *)aSelected
{
    NSLog(@"%@",aSelected);
//    [self.nativeArray addObject:aSelected];
    self.nativeArray = (NSMutableArray*)aSelected;
    
    [picker dismissViewControllerAnimated:YES completion:^{
        NSLog(@"%@",self.nativeArray);

        [self.collectionView reloadData];
    }];
    
}
- (void)didCancelDoImagePickerController
{
    //    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    NSLog(@"%@",image);
    [picker dismissViewControllerAnimated:YES completion:nil];
}
/**
 *  取消选择图片
 *
 *  @param picker
 */
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.nativeArray.count + self.theimageView.count > 9) {
        return 9;
    }
    return self.nativeArray.count + self.theimageView.count;
}
//定义展示的Section的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//每个UICollectionView展示的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"cell";
    ZXCollectionCell *cell    = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    [cell sizeToFit];
    if (indexPath.row >= 0 && indexPath.row < self.nativeArray.count)
    {
        cell.imgView.image = self.nativeArray[indexPath.row];
        cell.close.hidden = NO;
    }
    if (indexPath.row == self.nativeArray.count)
    {
        cell.imgView.image = imageName(self.theimageView[0]);
        cell.imgView.backgroundColor = [UIColor clearColor];
        cell.close.hidden = YES;
    }
    cell.delegate = self;
    
    return cell;
}
- (void)moveImageBtnClick:(ZXCollectionCell *)aCell
{
    NSIndexPath * indexPath = [self.collectionView indexPathForCell:aCell];
    NSLog(@"_____%ld",indexPath.row);
    if (self.nativeArray.count > 0)
    {
        [self.nativeArray  removeObjectAtIndex:indexPath.row];
        [self.collectionView reloadData];
    }
    else {
        
    }
    NSLog(@"%@",self.nativeArray);
}
#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((self.collectionView.frame.size.width)/5,(self.collectionView.frame.size.width)/5);
}
//定义每个UICollectionView 的间距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
//定义每个UICollectionView 纵向的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
//列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 1;
}
#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld",(long)indexPath.row);
    if (indexPath.row == self.nativeArray.count ) {
        [self performSelector:@selector(rightBtn) withObject:nil];
    }
    
}
//返回这个UICollectionView是否可以被选择
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (NSMutableArray*)theimageView
{
    if (_theimageView == nil) {
        _theimageView = [NSMutableArray array];
    }
    return _theimageView;
}
- (NSMutableArray*)nativeArray
{
    if (_nativeArray == nil) {
        _nativeArray = [NSMutableArray array];
    }
    return _nativeArray;
}
- (UIScrollView*)scrollView{
    if (_scrollView == nil) {
        _scrollView = [UIScrollView new];
        _scrollView.backgroundColor = [UIColor whiteColor];
        _scrollView.bounces = YES;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT+100);
    }
    return _scrollView;
}

@end
